# coding:utf-8
import os
import chardet
def travelDir(dirName):
	i = 0
	fileAllNames = []
	if os.path.isdir(dirName):  
	    for root, dirs, files in os.walk(dirName):
	    	for filename in files:
		    	fileAllName=root+'/'+filename
		    	fileAllNames.insert(i,fileAllName)
	return fileAllNames

#fileNameExtArr是允许通过的扩展名字符串数组
def filter(fileAllNamesArr, fileNameExtArr):
	fileAllNames = []
	i = 0
	for fileAllName in fileAllNamesArr:
		for ext in fileNameExtArr:
			if(os.path.splitext(fileAllName)[1] == ext):
				fileAllNames.insert(i,fileAllName)
				++i
				break
	return fileAllNames

def ascii2utf8(fileAllName):
    with open(fileAllName, 'rb') as f:
        s = f.read()
    if s.replace('\n','').replace(' ','') == '':
        return
    s1 = s.decode(chardet.detect(s)['encoding'].lower())
    with open(fileAllName, 'w') as f:
        f.write(s1.encode('utf-8'))
if __name__ == '__main__':
    fileAllNameArr = travelDir('/home/feng/note/code/note')
    filterFileNameArr = filter(fileAllNameArr,['.py','.txt'])
    for fileallname in filterFileNameArr:
        print fileallname
        ascii2utf8(fileallname)

